package org.future.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class WorkHandler implements Runnable{
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	private SimpleDateFormat simpleFormat = new SimpleDateFormat(
			                                  "yyyy-MM-dd HH:mm:ss:S");
	
	public WorkHandler(Socket socket)throws IOException{
		socket.setSoTimeout(1000*60*5);
		this.socket = socket;
		in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		out = new PrintWriter(socket.getOutputStream());
	}
	
	public void run() {
	    try{
	    	// start
	    	String time = simpleFormat.format(new Date());
	    	System.out.println(time + "-> connected succeed.");
	    	String msg = null;
	    	while((msg = in.readLine()) != null){
	    		out.println(echo(msg));
	    		out.flush();        // 此处的flush()非常重要，否则客户端无法收到消息
	    		if(msg.equalsIgnoreCase("bye")){
	    			break;
	    		}
	    	}
	    } catch(IOException e){
	    	e.printStackTrace();
	    } finally{
	    	try{
	    		if(socket != null){
		    		socket.close();
		    	}
	    	} catch(Exception e){
	    	}
	    	// end
	    	String time = simpleFormat.format(new Date());
	    	System.out.println(time + "-> connection closed.");
	    }
	}
	
	public String echo(String msg){
		return "server back:" + msg;
	}
}
